var myTableRef;
var isValidate;
var myMustacheTmpl = $('#myMustacheTmpl').val();
var myGoodsTmpl = $('#myGoodsTmpl').val();
var myGoodsTreesTmpl = $('#myGoodsTreesTmpl').val();
var min = 100;
var max = 9999999;
var init = 0;
var rules;
var oriGift = 0;
Mustache.parse(myMustacheTmpl);
Mustache.parse(myGoodsTmpl);
Mustache.parse(myGoodsTreesTmpl);
var pageName = "会员消费";
var myGoodsArray = {
	"myTest" : 0
};
var goodsTreesIdSetsStr = "";
var needMemberPassword = "";
var cardLevelDiscount = 100;
var globalCashDiscountMapping = "";
var globalCashDiscount = 100;

var goodsTreeSetting = {
	view : {
		selectedMulti : false,
		showTitle : false
	},
	data : {
		key : {
			title : "title"
		},
		simpleData : {
			enable : true,
			idKey : "dictId",
			pIdKey : "pId",
			rootPId : 0
		}
	},
	callback : {
		onClick : onClickTree
	}
};

function onClickTree(e, treeId, treeNode) {
	if (treeNode.level == 0 || treeNode.isParent || treeNode.type != 'goods') {
		return false;
	}
	if (!$('#cardNo').val()) {
		toastrError('请先查询会员信息');
		return false;
	}
	appendGoods(treeNode);
}

function appendGoods(goods) {
	// if goods exist
	if (myGoodsArray[goods.id] == 0) {
		return false;
	}
	goods.goodsDiscount = globalCashDiscount;
	goods.goodsPriceOnDiscount = formatDouble(+goods.goodsPrice
			* +goods.goodsDiscount / 100);
	var output = Mustache.render(myGoodsTmpl, goods);
	$('#myTbody').append(output);
	myGoodsArray[goods.id] = 0;
	calcMoneySum();
}

function calcMoneySum() {
	var sum = 0;
	var sumFact = 0;
	$('#myTbody .goodsPrice').each(function() {
		sum += (+$(this).val());
	});
	sum = sum * +cardLevelDiscount / 100;
	$('#myTbody .goodsPriceFact').each(function() {
		sumFact += (+$(this).val());
	});
	if (sum <= sumFact) {
		sumFact = sum;
	}
	$('#moneySum').val(formatDouble(sum));

	var giftMoney = oriGift;
	giftMoney = (giftMoney >= sum ? sum : giftMoney);
	$('#moneyGift').val(formatDouble(giftMoney));

	sumFact = (sumFact - giftMoney) <= 0 ? 0 : (sumFact - giftMoney);

	$('#moneyFactSum').val(formatDouble(sumFact));

	if (sumFact >= 0) {
		$('#saveOrUpdateModalBtn').removeAttr('disabled');
	} else {
		$('#saveOrUpdateModalBtn').attr('disabled', 'disabled');
	}
}

function drawGoodsTreeAndSelect(msg) {
	var goodsTreesSelect = msg.goodsTreesSelect;
	var output = Mustache.render(myGoodsTreesTmpl, msg);
	$('#goodsTreesDiv').append(output);

	$('#goodsTreesSelect').empty().append(goodsTreesSelect).select2().on(
			'select2:selecting', function(e) {
				if (!$('#cardNo').val()) {
					toastrError('请先查询会员');
					return false;
				} else {
					return true;
				}
			}).on('select2:select', function(e) {
		$('#goodsTreesDiv .ztree').hide();
		$('#' + e.params.data.id).show();
		if (globalCashDiscountMapping[e.params.data.id]) {
			globalCashDiscount = globalCashDiscountMapping[e.params.data.id];
		} else {
			globalCashDiscount = 100;
		}
	});

	var goodsTreesIdSets = msg.goodsTreesIdSets;
	var goodsTrees = msg.goodsTrees;
	for ( var index in goodsTreesIdSets) {
		var id = goodsTreesIdSets[index];
		var goodsTree = goodsTrees[index];
		$.fn.zTree.init($('#' + id), goodsTreeSetting, goodsTree);
	}
	$('#' + goodsTreesIdSets[0]).show();
	goodsTreesIdSetsStr = msg.goodsTreesIdSetsStr;
}

function drawPasswordDiv() {
	var needOperatorPassword = '${mmsOrgConfig.needOperatorPassword}';
	needMemberPassword = '${mmsOrgConfig.needMemberPassword}';
	if (needOperatorPassword == '1') {
		$('#needOperatorPasswordDiv').show();
	} else {
		$('#needOperatorPasswordDiv').hide();
	}
	if (needMemberPassword == '1') {
		$('#needMemberPasswordDiv').show();
	} else {
		$('#needMemberPasswordDiv').hide();
	}
	$('#memberPassword').on('focus', function() {
		$('#memberPasswordModal').modal({
			'backdrop' : 'static'
		});
	});
	$('#memberPasswordModal').on('shown.bs.modal', function() {
		$('input#memberPasswordTmp').val('').focus();
	});
	$("#memberPasswordModal").on('keypress', function(event) {
		if (event.keyCode == 13) {
			setMemberPassword();
		}
	});
	$("#memberPasswordModalBtn").on('click', function(event) {
		setMemberPassword();
	});
}

function setMemberPassword() {
	var tmpValue = $('#memberPasswordTmp').val();
	if (!tmpValue) {
		toastrError('请输入用户卡密码');
		return false;
	}
	$('#memberPassword').val(tmpValue);
	$('#memberPasswordModalCloseBtn').click();
}

function calcTrMoneyOnKeyUp(tr) {
	var goodsNum = tr.find('.goodsNum').val();
	var goodsPriceSingle = tr.find('.goodsPriceSingle').val();
	var goodsDiscount = tr.find('.goodsDiscount').val();
	var sum = formatDouble(+goodsNum * +goodsPriceSingle * +goodsDiscount / 100);
	tr.find('.goodsPrice').val(sum);
	tr.find('.goodsPriceFact').val(sum);
	calcMoneySum();
}

$(function() {

	drawPasswordDiv();
	$('#mmsOrgConfigId').val('${mmsOrgConfig.id}');

	$('#myTbody').on('click', '.remove', function() {
		var tr = $(this).parents('tr');
		tr.remove();
		delete myGoodsArray[tr.attr('id')];
		calcMoneySum();
	});

	$('#myTbody').on('keyup', 'input.goodsPriceFact', function() {
		calcMoneySum();
	});

	$('#moneyFactSum').on('keyup', function() {
		var sum = $('#moneySum').val();
		var sumFact = $('#moneyFactSum').val();
		if (sumFact >= sum) {
			sumFact = sum;
		}
		// $('#moneyFactSum').val(formatDouble(sumFact));
	});

	$('#myTbody').on('keyup', 'input.goodsNum', function() {
		calcTrMoneyOnKeyUp($(this).parents('tr'));
	});

	$('#myTbody').on('keyup', 'input.goodsPriceSingle', function() {
		calcTrMoneyOnKeyUp($(this).parents('tr'));
	});

	$('#myTbody').on('keyup', 'input.goodsDiscount', function() {
		calcTrMoneyOnKeyUp($(this).parents('tr'));
	});

	$('#saveOrUpdateModalBtn').attr('disabled', 'disabled');
	$('#cardNo').val('');
	$('#id').val('');

	$("#mySearchForm").keypress(function(event) {
		if (event.keyCode == 13) {
			$("#mySearchFormBtn").click();
			return false;
		}
	});

	$.ajax({
		type : "POST",
		url : '${home}/mms/cash/expense/goodsTree',
		data : $("#yourFormId").serialize(),
		cache : false,
		dataType : "json",
		success : function(r) {
			drawGoodsTreeAndSelect(r.msg);
		}
	});

	isValidate = $("form#myForm").validate({
		rules : {
			goodsNum : {
				required : true,
				digits : true,
				min : 1,
				max : 99
			},
			goodsDiscount : {
				required : true,
				digits : true,
				min : 1,
				max : 100
			},
			goodsPriceFact : {
				required : true,
				number : true,
				min : 0
			},
			moneySum : {
				required : true,
				number : true,
				min : 0
			},
			moneyFactSum : {
				required : true,
				number : true,
				min : 0
			// lessthan : "#moneySum"
			},
			goodsRemark : {
				maxlength : 10
			},
			remark : {
				maxlength : 20
			},
			operatorPassword : {
				required : true
			}
		},
		messages : {
			money : {
				required : '请输入消费金额',
				digits : "请输入正整数"
			},
			moneyFactSum : {
				lessthan : '实收金额应小于应收金额'
			}
		}
	});

	$("button.moneyBtn").on("click", function() {
		if (!$('#cardNo').val()) {
			toastrError('请先查询会员');
			return false;
		}
		$('#money').val($(this).val()).keyup();
	});

	$('#mySearchFormBtn')
			.on(
					'click',
					function() {
						$
								.ajax({
									type : "POST",
									url : '${home}/mms/member/mmsMember/get',
									data : $("#mySearchForm").serialize(),
									cache : false,
									dataType : "json",
									success : function(r) {
										$('#remark').val('');
										if (r.ret == 0) {
											var output = Mustache.render(
													myMustacheTmpl, r);
											$("#myInfoDiv").show();
											$("#myInfoDiv").empty().append(
													output);
											$('#cardId').val(r.msg.mmsCard.id);
											$('#cardNo').val(
													r.msg.mmsCard.cardNo);
											$('#cardMoney').val(
													r.msg.mmsCard.money);
											$('#moneyGift')
													.val(
															r.msg.mmsCardOrgInfo.giftMoney);
											$('#mmsCardOrgInfoId').val(
													r.msg.mmsCardOrgInfo.id);
											oriGift = r.msg.mmsCardOrgInfo.giftMoney;
											cardLevelDiscount = r.msg.mmsCard.discount;
											globalCashDiscountMapping = r.msg.mmsCashDiscount;
											globalCashDiscount = globalCashDiscountMapping[r.msg.mmsOrgConfig.orgId];
											$('#errorDiv').hide();
											calcMoneySum();
										} else {
											$('#errorDiv').show();
											$('#cardNo').val('');
											$('#moneyGift').val('0');
											oriGift = 0;
											cardLevelDiscount = 100;
											$("#myInfoDiv").empty().hide();
										}
										$('#cardLevelDiscount').val(
												cardLevelDiscount);
									}
								});
					});

	$('#myBtn').on(
			"click",
			function() {
				if (isValidate.form() == false) {
					return false;
				}
				if (!$('#cardNo').val()) {
					toastrError('请先查询会员信息');
					return false;
				}
				if ($('#myTbody tr').length < 1) {
					toastrError('请选择需要消费的商品');
					return false;
				}
				if (needMemberPassword == '1' && !$('#memberPassword').val()) {
					toastrError('请输入用户密码');
					return false;
				}
				var cardNo = $('#cardNo').val();
				var moneySum = $('#moneySum').val();
				var moneyFactSum = $('#moneyFactSum').val();
				var moneyGift = $('#moneyGift').val();
				var cardMoney = $('#cardMoney').val();

				if ((+moneyFactSum) > (+cardMoney)) {
					toastrError('如果会员已充值，请重新查询会员', '会员卡余额不足');
					$('#saveOrUpdateModalBtn').removeAttr('disabled');
					return false;
				}

				var confirmMsg = '是否确认为卡：【' + cardNo + "】进行消费,消费金额为：￥【"
						+ formatMoney(moneySum) + "】,实收金额为：￥【"
						+ formatMoney(moneyFactSum) + "】" + ",使用返现金额为：￥【"
						+ formatMoney(moneyGift) + "】";

				$('#myConfirm').html(confirmMsg);
				$('#saveOrUpdateModal').modal({
					'backdrop' : 'static'
				});
			});

	$('#saveOrUpdateModalBtn').on("click", function() {
		$('#saveOrUpdateModalCloseBtn').click();
		$('#myBtn').attr('disabled', 'disabled');
		mask('为会员卡消费中,请稍候...');
		$.ajax({
			type : "POST",
			url : '${home}/mms/cash/expense/save',
			data : $("#myForm").serialize(),
			cache : false,
			dataType : "json",
			success : function(r) {
				if (r.ret == 0) {
					$('#mmsTradeRecordId').val(r.mmsTradeRecordId);
					$('#mmsCardId').val(r.mmsCardId);
					$('form#successForm').submit();
					return true;
				} else {
					$('#myBtn').removeAttr('disabled');
					unmask();
					toastr.clear();
					toastrError(r.msg, '操作失败,失败原因:');
				}
			},
			error : function(r) {
				unmask();
				$('#myBtn').removeAttr('disabled');
				toastr.clear();
				toastrError('系统异常,请稍后重试');
			}
		});
	});
	$("#mySearchFormResetBtn").on('click', function() {
		$("#mySearchForm")[0].reset();
	});

	$('#deleteModalConfirmBtn').on("click", function() {
		$(this).button('操作进行中...');
		$.ajax({
			type : "POST",
			url : '${home}/mms/member/deleteMmsMember',
			data : $("#myForm").serialize(),
			cache : false,
			dataType : "json",
			timeout : 5000,
			success : function(r) {
				$('#deleteModalBtn').button('reset');
				$('#deleteModalCloseBtn').click();
				myTableRef.ajax.reload();
				info("成功删除记录");
			},
			error : function(jqXHR, textStatus, errorThrown) {
				$('#deleteModalBtn').button('reset');
				$('#deleteModalCloseBtn').click();
			}
		});
	});

	$("#saveOrUpdateModalCloseBtn").on('click', function() {
		$("label.error").hide();
		$(".error").removeClass("error");
	});

	myTableRef = $('#myTable').DataTable(
			{
				"autoWidth" : true,
				"pageLength" : 10,
				"autoWidth" : true,
				"processing" : true,
				"serverSide" : true,
				"deferRender" : true,
				"paging" : true,
				"filter" : false,
				"lengthChange" : false,
				"ordering" : false,
				"orderClasses" : false,
				"pagingType" : "full_numbers",
				"info" : true,
				"ajax" : {
					"url" : "${home}/mms/member/listMmsMember",
					"type" : "POST",
					"dataType" : 'json',
					"data" : function(d) {
						$('input#start').val(d.start);
						$('input#length').val(d.length);
						return $('#mySearchForm').serialize();
					}
				},
				"initComplete" : function() {
				},
				"columns" : [
						{
							"mData" : function(source, type, val) {
								return '<input id="myIds" name="myIds" value="'
										+ source[0].id + '" type="checkbox">';
							}
						}, {
							"mData" : function(source, type, val) {
								return source[0].cardNo;
							}
						}, {
							"mData" : function(source, type, val) {
								return source[1] ? source[1].realName : "";
							}
						}, {
							"mData" : function(source, type, val) {
								return source[1] ? source[1].mobile : "";
							}
						}, {
							"mData" : function(source, type, val) {
								return "";
							}
						}, {
							"mData" : function(source, type, val) {
								return source[0].state;
							}
						}, {
							"mData" : function(source, type, val) {
								return source[0].money;
							}
						}, {
							"mData" : function(source, type, val) {
								return source[0].score;
							}
						}, {
							"mData" : function(source, type, val) {
								return "100%";
							}
						}, {
							"mData" : function(source, type, val) {
								return source[0].creator;
							}
						} ]
			});
	// end datatable
	bindAutoComplete();
	bindAutoCompleteOnToken();
});

function bindAutoComplete() {
	$('#mySelect').select2({
		placeholder : "通过商品代码，商品名称快速选择商品",
		minimumInputLength : 1,
		ajax : {
			url : "${home}/mms/goods/get/autocomplete",
			dataType : 'json',
			data : function(params) {
				return {
					q : params.term, // search term
					p : goodsTreesIdSetsStr
				};
			},
			delay : 250,
			processResults : function(data, page) {
				return {
					results : data.msg
				};
			},
			cache : true
		}
	}).on('select2:select', function(e) {
		appendGoods(e.params.data);
		$('#mySelect').val('').trigger('change');
	});
}
function bindAutoCompleteOnToken() {
	$('#token').select2({
		placeholder : "输入会员手机号或者会员卡号快速查询会员",
		minimumInputLength : 4,
		ajax : {
			url : "${home}/mms/member/mmsMember/get/autocomplate",
			dataType : 'json',
			data : function(params) {
				return {
					q : params.term
				// search term
				};
			},
			delay : 250,
			processResults : function(data, page) {
				return {
					results : data.msg
				};
			},
			cache : true
		}
	}).on('select2:select', function(e) {
		$('#cardId').val(e.params.data.id);
		$("#mySearchFormBtn").click();
	});
}
